import { Vue, Watch } from 'vue-property-decorator';
import ColumnUtil from '../utils/column-util';
import Invest from '@/common/dict/invest';
import { getActiveMenuCode, getUser } from '@/utils/user-util';
import { getTableLayout } from '@/common/api/commonApi';
import moment from 'moment';
import { cancelCommonOrder, trialCalculate } from '@/common/api/instruction';
import { UUID } from '@/utils/tools';
import { queryMarginTradingPosiotions, queryMarginTradingStocks } from '../api/margin-trading';

// 融资融券指令下单公共类
export default class MarginTradingOderClass extends Vue {
    ColumnUtil = new ColumnUtil();
    Invest: any = new Invest();
    pages = { currentPage: 1, pageSize: 25 };

    // 显示的标签页
    positionActivePane: string = '1';

    // 融资标的券信息
    financingStockListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.financingStockColumns,
        height: '100%',
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 融资标的券持仓
    financingPositionListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.underlyingPositionColumns,
        height: '100%',
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 融券标的券信息
    marginStockListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.marginStockColumns,
        height: '100%',
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 融券标的券持仓
    marginPositionListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.underlyingPositionColumns,
        height: '100%',
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 担保券信息
    guaranteeStockListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.GuaranteeStockColumns,
        height: '100%',
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 担保券持仓信息
    guaranteePositionListMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: this.ColumnUtil.GuaranteePositionColumns,
        height: '100%',
        hidePage: false,
        checked: { on: false, option: false },
    };

    // 试算结果信息
    trailResultMsg: any = {
        calcTime: '', // 下单/试算时间
        takeTime: '', // 计算耗时
        riskResult: '', // 风控结果
        riskResultTable: [], // 风控结果表数据
    };

    riskResultTable: any[] = []; // 风控结果表数据

    layoutDialog: boolean = false; // 试算结果表布局设置
    calcLoading: boolean = false;
    tableKey: number = 0;
    tableColumns = this.ColumnUtil.riskTableColumns; // 试算结果表格全部字段
    showFieldList: any[] = []; // 要显示的表格列
    selectedFieldList: any[] = []; // 已选择字段列表
    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '产品代码', id: 'fundCode', sortable: true },
        { content: '产品名称', id: 'fundNameSt', sortable: false },
    ];

    entryTypeArr: any[] = []; // 风险类型
    ThresholdTypeArr: any[] = []; // 阈值类型

    iconDom: any = null; // 图标dom

    entryGroupDialog: boolean = false; // 条目组设置弹框显示
    resourceCode: string = '';

    // 指令
    instruction: any = {
        fundCode: '',
    };
    riskOrderResultAfterKey: number = 0;
    orderCancelShow: boolean = false;
    renderCountKey: number = 0;
    positionLoading: boolean = false;
    tableSelectedStockInfo: any = {};

    // 融资、融券、担保券查询表单
    queryForm: any = {
        sort: '',
    };

    // 融资、融券、担保券持仓查询表单
    queryPositionForm: any = {
        sort: '',
    };

    selectEntryGroupCode = {
        calculateEntryGroup: [],
        excludeEntryGroup: [],
    };
    riskOrderResultTable: any[] = [];
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    // 表单校验字段
    verifyParams: any = {
        fundCode: '产品代码',
        fundAccountCode: '组合编码',
        stockCode: '证券代码',
        orderPrice: '指令价格',
        orderAmount: '指令数量',
        orderBalance: '指令金额',
    };

    oldOuterOrderCode: string = '';
    isUpdate: boolean = false;
    serialNo: string = '';
    refreshNumber: number = 0;

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        const property = column['property'];
        return row[property].includes(option.data);
    }

    // 转表格筛选下拉框数据
    objToArr(param) {
        const list = [];
        for (const key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }

    /* ******************************* 持仓相关start ****************************** */
    /**
     * 查询融资标的券、融券标的券、担保券
     * @param pages
     * @param type 1-担保，2-融资，3-融券
     */
    queryStockList(pages: any, type: string) {
        // this.pages = pages;
        this.positionLoading = true;
        queryMarginTradingStocks({
            paging: pages,
            type: type,
            ...this.queryForm,
        })
            .then((res: any) => {
                const stockCodeData: any = res.list;
                this.handleStockStatus(stockCodeData, this.instruction?.stockCode);
                if (type == '1') {
                    this.guaranteeStockListMsg.returnData.data = stockCodeData;
                    this.guaranteeStockListMsg.returnData.total = res.total;
                } else if (type === '2') {
                    this.financingStockListMsg.returnData.data = stockCodeData;
                    this.financingStockListMsg.returnData.total = res.total;
                } else if (type === '3') {
                    this.marginStockListMsg.returnData.data = stockCodeData;
                    this.marginStockListMsg.returnData.total = res.total;
                }
                this.positionLoading = false;
            })
            .catch(err => {
                this.yh_message_error(err);
                this.positionLoading = false;
            });
    }

    /**
     * 融资标的券、融券标的券、担保券表头搜索
     * @param filterList 筛选字段
     * @param type 1-担保，2-融资，3-融券
     */
    handleFilterStock(filterList: any, type: string) {
        this.queryForm = {
            sort: '',
        };
        if (filterList.length) {
            filterList.forEach(ele => {
                if (ele.property === 'marketName') {
                    this.queryForm['marketNo'] = ele?.values;
                } else {
                    this.queryForm[ele.property] = ele?.datas[0] || '';
                }
            });
        }
        this.queryStockList(this.pages, type);
    }

    /**
     * 融资标的券、融券标的券、担保券表头排序
     * @param args 排序字段
     * @param type 1-担保，2-融资，3-融券
     */
    handleSortStock(args: any, type: string) {
        const sortType = args[1] == 'asc' ? 'ASC' : args[1] == 'desc' ? 'DESC' : '';
        let sort = '';
        if (sortType) {
            sort = this.handleSortField(args[0], sortType);
        } else {
            sort = '';
        }
        this.queryForm.sort = sort;
        this.queryStockList(this.pages, type);
    }

    /**
     * 查询融资标的券持仓、融券标的券持仓、担保券持仓
     * @param pages 分页
     * @param type 1-担保，2-融资，3-融券
     */
    queryPositionList(pages: any, type: string) {
        // this.pages = pages;
        queryMarginTradingPosiotions({
            paging: pages,
            type: type,
            ...this.queryPositionForm,
            fundCode: this.instruction.fundCode,
        })
            .then(res => {
                const stockCodeData: any = res.list;
                this.handleStockStatus(stockCodeData, this.instruction?.stockCode);
                if (type == '1') {
                    this.guaranteePositionListMsg.returnData.data = stockCodeData;
                    this.guaranteePositionListMsg.returnData.total = res.total;
                } else if (type === '2') {
                    this.financingPositionListMsg.returnData.data = res.list;
                    this.financingPositionListMsg.returnData.total = res.total;
                } else if (type === '3') {
                    this.marginPositionListMsg.returnData.data = stockCodeData;
                    this.marginPositionListMsg.returnData.total = res.total;
                }
                this.positionLoading = false;
            })
            .catch(err => {
                this.yh_message_error(err);
                this.positionLoading = false;
            });
    }

    /**
     * 持仓表表头筛选
     * @param filterList 筛选字段
     * @param type 1-担保，2-融资，3-融券
     */
    handleFilterPosition(filterList: any, type: string) {
        this.queryPositionForm = {
            sort: '',
        };
        if (filterList.length) {
            filterList.forEach(ele => {
                this.queryPositionForm[ele.property] = ele?.datas[0] || '';
            });
        }
        this.queryPositionList(this.pages, type);
    }

    /**
     * 持仓表表头排序
     * @param args 排序字段和排序类型
     * @param type 1-担保，2-融资，3-融券
     */
    handleSortPosition(args: any, type: string) {
        const sortType = args[1] == 'asc' ? 'ASC' : args[1] == 'desc' ? 'DESC' : '';
        let sort = '';
        if (sortType) {
            sort = this.handleSortField(args[0], sortType);
        } else {
            sort = '';
        }
        this.queryPositionForm.sort = sort;
        this.queryPositionList(this.pages, type);
    }

    // 获取排序字段
    handleSortField(name: string, order: string): string {
        let value = '';
        let field = '';
        const allFields = this.ColumnUtil.MarginTradingSortField;
        for (const key in allFields) {
            if (name === key) {
                field = allFields[key];
            }
        }
        value = field + ' ' + order;
        return value;
    }

    /**
     * 设置券选中状态
     * @param stockCodeData 当前所有券数据
     * @param selectStockCode 选中券
     */
    handleStockStatus(stockCodeData: any, selectStockCode: string): void {
        stockCodeData.forEach(ele => {
            if (selectStockCode === ele.stockCode) {
                this.$set(ele, 'disabled', true);
            } else {
                this.$set(ele, 'disabled', false);
            }
        });
    }

    /* ******************************* 持仓相关end ****************************** */

    /* ******************************* 试算、下单start *************************** */

    // 表单校验
    handleVerifyInstructionParam(instruction: any) {
        if (instruction.orderPriceType === '2') {
            delete this.verifyParams.orderPrice;
        }
        for (const key in this.verifyParams) {
            if (!instruction[key]) {
                this.yh_message_warn(this.verifyParams[key] + '不可为空');
                return false;
            }
        }
        return true;
    }

    /**
     * 生成完整的指令表单
     * @param instruction 指令表单
     */
    createInstruction(instruction: any): any {
        instruction.instructionType = '15';
        instruction.orderUser = getUser().userCode;
        instruction.outerOrderCode = UUID() + '-' + new Date().getTime();
        instruction.requestId = UUID() + '-' + new Date().getTime();
        if (instruction.orderPriceType === '2') {
            instruction.orderPrice = instruction.closePrice;
        }
        return instruction;
    }

    /**
     * 指令表单提交
     * @param orderType 下单类型 1试算、2下单
     */
    handleFormSubmit(orderType: string) {
        const isUpdate = this.isUpdate;

        // 表单校验
        const verify: any = this.handleVerifyInstructionParam(this.instruction);
        if (!verify) {
            return;
        }

        this.instruction = this.createInstruction(this.instruction);
        this.instruction.orderType = orderType;
        const form: any = {
            orderType: orderType,
            multiType: '2',
            requestId: this.instruction.requestId,
            instructionType: '15',
            outOrderBatchCode: UUID() + new Date().getTime(),
            tradeUser: getUser().userCode,
            calculateEntryGroup: this.selectEntryGroupCode.calculateEntryGroup,
            excludeEntryGroup: this.selectEntryGroupCode.excludeEntryGroup,
            instList: [this.instruction],
        };
        if (orderType == '2') {
            this.instruction.cancelType = '1';
            form.cancelType = '1';
        }
        if (isUpdate) {
            form.excludeSerialNoSet = [this.serialNo];
        }
        const start = window.performance.now();
        this.trailResultMsg.calcTime = moment().format('YYYY-MM-DD HH:mm:ss');
        trialCalculate(form).then((res: any) => {
            const end = window.performance.now();
            this.trailResultMsg.takeTime = ((end - start) / 1000).toFixed(3) + '秒';
            this.trailResultMsg.riskResult = res.thresholdType;
            const data = res.resultList || [];

            // 根据产品代码 匹配产品名称
            data.forEach(ele => {
                ele.requestId = res.requestId;
                ele.fundNameSt = this.instruction.fundNameSt;
                ele.stockNameSt = this.instruction.stockNameSt;
            });
            this.trailResultMsg.riskResultTable = JSON.parse(JSON.stringify(data));
            this.riskOrderResultTable = JSON.parse(JSON.stringify(data));
            this.riskResultTable = JSON.parse(JSON.stringify(data));

            if (orderType == '1') {
                this.orderCancelShow = false;
                this.yh_message_success('提交试算信息成功');
            } else {
                if (this.trailResultMsg.riskResult == '0') {
                    this.orderCancelShow = false;
                    this.handleClickButtonReset();

                    // 清空试算结果
                    this.trailResultMsg = {
                        calcTime: '',
                        takeTime: '',
                        riskResult: '',
                        riskResultTable: [],
                    };
                    const h = this.$createElement;
                    this.$message.success({
                        message: h('p', null, [
                            h('span', null, '本次风控下单结果为'),
                            h('span', { style: 'color: #70b603' }, '"合规"'),
                            h('span', null, '，已下单成功'),
                        ]),
                        showClose: true,
                        customClass: 'messageStyle',
                    });
                    if (isUpdate) {
                        this.handleUpdateCancel();
                    }
                    this.isUpdate = false;
                } else {
                    this.riskOrderResultAfterKey++;
                    this.orderCancelShow = true;
                }
                // if (isUpdate) {
                //     this.handleUpdateCancel();
                // }
            }
            this.$emit('getResult', this.trailResultMsg);
        });
    }

    // 重置按钮点击事件
    handleClickButtonReset() {
        this.renderCountKey++;
        this.tableSelectedStockInfo = {};
        this.isUpdate = false;
        this.$emit('reset', null);
    }

    // 处理选择结果返回
    riskResultContinue() {
        this.calcLoading = false;
        // 重置表单
        this.handleClickButtonReset();
        // 清空试算结果
        this.trailResultMsg = {
            calcTime: '',
            takeTime: '',
            riskResult: '',
            riskResultTable: [],
        };
        this.$emit('getResult', this.trailResultMsg);
        if (this.isUpdate) {
            this.handleUpdateCancel();
        }
        this.yh_message_success('指令下达成功');
        this.isUpdate = false;
    }

    // 修改指令撤单
    handleUpdateCancel() {
        cancelCommonOrder({
            cancelOrderType: '2',
            tradeUser: getUser().userCode, // 当前用户
            tradeUserName: getUser().userName, // 当前用户
            orderType: '4',
            instructionType: '10',
            instNo: '',
            originOuterOrderCode: this.oldOuterOrderCode,
            outerOrderCode: UUID() + '-' + new Date().getTime(),
            requestId: UUID() + '-' + new Date().getTime(),
            delOriginOuterOrderCodeList: [this.oldOuterOrderCode],
        })
            .then(res => {})
            .catch(err => {
                this.yh_message_success(err);
            });
    }

    // 取消
    riskResultCancel() {
        this.calcLoading = false;
        this.trailResultMsg.riskResultTable = [];
        cancelCommonOrder({
            cancelOrderType: '2',
            tradeUser: getUser().userCode, // 当前用户
            tradeUserName: getUser().userName, // 当前用户
            orderType: '4',
            instructionType: '10',
            instNo: '',
            originOuterOrderCode: this.instruction.outerOrderCode,
            outerOrderCode: UUID() + '-' + new Date().getTime(),
            requestId: UUID() + '-' + new Date().getTime(),
            delOriginOuterOrderCodeList: [this.instruction.outerOrderCode],
        }).then(res => {
            this.yh_message_success('已终止指令下达');
            this.orderCancelShow = false;
        });
    }

    /* ******************************* 试算、下单end *************************** */

    // /* **************************** 布局设置start ***************************** */
    // // 获取页面布局信息
    // async queryLayout() {
    //     this.calcLoading = true;
    //     const resList: any = await new Promise((resolve, reject) => {
    //         getTableLayout('MARGIN_TRADING_ORDER')
    //             .then((res: any) => {
    //                 resolve(res);
    //             })
    //             .catch(err => {
    //                 reject(err);
    //             });
    //     });
    //     if (resList) {
    //         this.selectedFieldList = JSON.parse(resList);
    //         this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
    //         this.calcLoading = false;
    //     } else {
    //         this.showFieldList = this.tableColumns;
    //         this.selectedFieldList = this.tableColumns;
    //         this.calcLoading = false;
    //     }
    //     this.showFieldList.forEach((ele: any) => {
    //         if (['fundCode', 'stockCode', 'entryCode'].includes(ele.id)) {
    //             this.$set(ele, 'sortable', true);
    //         }
    //         if (['fundCode', 'fundNameSt', 'stockCode', 'stockNameSt', 'entryCode', 'entryName'].includes(ele.id)) {
    //             this.$set(ele, 'filterMethod', this.filterHandler);
    //             this.$set(ele, 'filters', [{ data: '' }]);
    //             this.$set(ele, 'search', true);
    //         }
    //         if (ele.id == 'entryType') {
    //             this.$set(ele, 'filterMethod', this.filterEntryTypeMethod);
    //             this.$set(ele, 'filters', this.entryTypeArr);
    //         }
    //         if (ele.id == 'thresholdType') {
    //             this.$set(ele, 'filterMethod', this.filterThresholdType);
    //             this.$set(ele, 'filters', this.ThresholdTypeArr);
    //         }

    //         // 重新渲染表格
    //         this.changeTable();
    //         this.tableKey++;
    //     });
    // }

    // /**
    //  * 提交成功后回调
    //  * @param {Object} 回调数据
    //  */
    // async onSubmit(data) {
    //     await this.queryLayout();
    //     this.iconDom = null;
    //     this.changeTable();
    //     this.tableKey++;
    // }

    // changeTable() {
    //     this.$nextTick(() => {
    //         const icon = [];
    //         if (!this.iconDom) {
    //             const obj = document.querySelector('.risk-order-bottom');
    //             this.iconDom = obj.querySelectorAll('.vxe-icon--funnel');
    //             this.iconDom.forEach((ele: any, index) => {
    //                 if (!['风险类型', '阈值类型'].includes(ele.parentNode.parentNode.children[0].innerHTML)) {
    //                     icon.push(index);
    //                 }
    //             });
    //             for (let i = 0; i < 8; i++) {
    //                 icon.forEach(ele => {
    //                     if (ele === i) {
    //                         this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
    //                     }
    //                 });
    //             }
    //         }
    //     });
    // }

    // filterThresholdType({ value, row, column }) {
    //     return row.thresholdType == value;
    // }

    // filterEntryTypeMethod({ value, row, column }) {
    //     return row.entryType == value;
    // }

    // /* ************************** 布局设置end *******************************/

    /* ************************************ 条目组设置start ********************************** */
    openEntryGroupDialogs() {
        this.resourceCode = getActiveMenuCode().defaultActive;
        this.entryGroupDialog = true;
    }

    getEntryGroups(value: any) {
        this.selectEntryGroupCode.calculateEntryGroup = value.calculateEntryGroup;
        this.selectEntryGroupCode.excludeEntryGroup = value.excludeEntryGroup;
    }

    closeEntryDialogs() {
        this.entryGroupDialog = false;
        this.getUserSelectEntryGroupList();
    }

    getUserSelectEntryGroupList() {
        this.resourceCode = getActiveMenuCode().defaultActive;
        this.$axios.get('/entry/group/user/select/list/' + this.resourceCode).then((res: any) => {
            res = res || [];
            const selectEntryGroupCode = {
                calculateEntryGroup: res.filter(item => item.instGroupType === '1' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
                excludeEntryGroup: res.filter(item => item.instGroupType === '2' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
            };
            this.selectEntryGroupCode.calculateEntryGroup = selectEntryGroupCode.calculateEntryGroup;
            this.selectEntryGroupCode.excludeEntryGroup = selectEntryGroupCode.excludeEntryGroup;
        });
    }
    /* ************************************ 条目组设置end ********************************** */
}
